//package com.plian.system.service.hr.abroad.impl;
//
//import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.plian.Tools.*;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.cache.UserCache;
//import com.plian.system.common.status.CheckStatus;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.constant.yth.YthConstant;
//import com.plian.system.dto.hr.abroad.AbroadDeclarationDTO;
//import com.plian.system.entity.hr.abroad.AbroadDeclaration;
//import com.plian.system.entity.sys.ApprovalMessage;
//import com.plian.system.entity.sys.Org;
//import com.plian.system.mapper.hr.abroad.AbroadDeclarationMapper;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.service.hr.abroad.IAbroadDeclarationService;
//import com.plian.system.service.sys.code.IFormCodeService;
//import com.plian.system.service.sys.message.IApprovalMessageService;
//import com.plian.system.service.sys.orgzation.IOrgService;
//import com.plian.system.service.sys.user.ISysUserService;
//import com.plian.system.service.wf.FormWorkflowService;
//import com.plian.system.vo.hr.abroad.AbroadDeclarationVO;
//import com.plian.system.vo.report.HeaderVO;
//import com.plian.system.vo.report.ReportReturnVO;
//import com.plian.system.vo.report.ReportVO;
//import com.plian.system.vo.yth.YthResult;
//import com.plian.system.wrapper.hr.abroad.AbroadDeclarationWrapper;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.GZW_TYPE;
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//
///**
// * 因公出国（境）计划申报管理 服务实现类
// *
// * @author gangan
// * @since 2019-12-02
// */
//@Slf4j
//@Service
//@AllArgsConstructor
//public class AbroadDeclarationServiceImpl extends BaseServiceImpl<AbroadDeclarationMapper, AbroadDeclaration> implements IAbroadDeclarationService, BaseFlowService {
//
//	private FormWorkflowService formWorkflowService;
//
//	private IFormCodeService formCodeService;
//
//	private AbroadDeclarationWrapper abroadDeclarationWrapper;
//
//	private IOrgService orgService;
//
//	private ISysUserService userService;
//
//	private IApprovalMessageService approvalMessageService;
//
//    @Override
//	@Transactional(rollbackFor=RuntimeException.class)
//    public boolean saveOrUpdate(AbroadDeclaration abroadDeclaration) {
//		if(abroadDeclaration.getStatus()==null){
//			abroadDeclaration.setStatus(FormStatusConstant.UNREVIEWED);
//		}
//        return super.saveOrUpdate(abroadDeclaration);
//    }
//
//    @Override
//    public boolean deleteLogic(List<Long> ids) {
//		for (Long id : ids) {
//			AbroadDeclaration abroadDeclaration = getById(id);
//			if (abroadDeclaration == null) {
//				return false;
//			} else if (abroadDeclaration.getStatus() != null &&
//					(abroadDeclaration.getStatus() != FormStatusConstant.STASH && abroadDeclaration.getStatus() != FormStatusConstant.UNREVIEWED)) {
//				return false;
//			}
//			formWorkflowService.deleteProcessInstance(String.valueOf(id));
//		}
//		return super.deleteLogic(ids);
//    }
//
//    @Override
//    public HashMap<String,Object> commit(String id) {
//		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW,null);
//
//		//将需要提交的流程变量返回，用于工作流侧
//		return new HashMap<String,Object>();
//    }
//
//    @Override
//    public Boolean finish(String id) {
//		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH,"审批通过");
//    }
//
//    @Override
//    public Boolean reject(String id, int formState, String comment) {
//		return handleStatus(Long.valueOf(id), formState,null);
//    }
//
//    /**
//     * 统一处理状态机事件方法
//     * @param id 主键
//     * @param updateStatus 更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus,String comment) {
//        try {
//            AbroadDeclaration abroadDeclaration = getById(id);
//			/**
//			 * 设置审批人和审批时间
//			 */
//			if (updateStatus == FormStatusConstant.FINISH){
//				abroadDeclaration.setApprovedUser(TokenUtil.getTokenUserId());
//				Date now = DateUtil.now();
//				abroadDeclaration.setApprovedTime(now);
//			}
//			if (StringUtil.isNotBlank(abroadDeclaration.getDataSource()) &&
//					StringUtil.isNotBlank(abroadDeclaration.getDataSourceId())){
//				if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT){
//					ApprovalMessage approvalMessage = new ApprovalMessage();
//					approvalMessage.setDataSourceId(abroadDeclaration.getDataSourceId());
//					approvalMessage.setOpinion(comment);
//					approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
//					approvalMessage.setIsSend(1);
//					approvalMessage.setDataSourceType(GZW_TYPE);
//					if (abroadDeclaration.getDataSource().equals(YthConstant.DATA_NINGBO)) {
//						approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
//						approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
//						approvalMessage.setFormType(FormTypeConstant.HR_ABROAD_DECLARATION_FORM);
//						approvalMessage.setFilingCode(abroadDeclaration.getCode());
//					}
//					approvalMessageService.save(approvalMessage);
//				}
//			}
//
//            abroadDeclaration.setStatus(updateStatus);
//            updateById(abroadDeclaration);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//
//	@Override
//	public ReportReturnVO report(AbroadDeclarationDTO abroadDeclarationDTO){
//		ReportReturnVO reportReturnVO = new ReportReturnVO();
//		ReportVO reportVO = new ReportVO();
//
//		reportVO.addHeader(HeaderVO.builder().key("declaringUnitName").title("企业名称").build())
//			.addHeader(HeaderVO.builder().key("declarationsCategoryName").title("申报类别").build())
//			.addHeader(HeaderVO.builder().key("groupName").title("团组名称").build())
//			.addHeader(HeaderVO.builder().key("groupUnitName").title("组团单位").build())
//			.addHeader(HeaderVO.builder().key("commanderName").title("团长姓名").build())
//			.addHeader(HeaderVO.builder().key("companyJobName").title("单位职务").build())
//			.addHeader(HeaderVO.builder().key("mission").title("出访任务").build())
//			.addHeader(HeaderVO.builder().key("visitingCountriesAreas").title("出访国家（地区）").build())
//			.addHeader(HeaderVO.builder().key("groupMembersNumber").title("团组人数").build())
//			.addHeader(HeaderVO.builder().key("travelTime").title("出访时间").build())
//			.addHeader(HeaderVO.builder().key("stayOutsideDays").title("在外停留天数").build())
//			.addHeader(HeaderVO.builder().key("cadresNumber").title("团组中市管干部人数").build())
//			.addHeader(HeaderVO.builder().key("expensesSource").title("费用来源").build())
//			.addHeader(HeaderVO.builder().key("isFinancialBudget").title("是否列入年度财务预算").build())
//			.addHeader(HeaderVO.builder().key("abroadSituation").title("团组中市管（委管）领导人员前两次因公出国（境）情况").build())
//			.addHeader(HeaderVO.builder().key("remark").title("备注").build());
//
//		List<AbroadDeclarationVO> list = abroadDeclarationWrapper.entityToVO(baseMapper.reportDataPage(abroadDeclarationDTO.getDeclaringUnitIds(),
//				abroadDeclarationDTO.getDeclarationsCategoryId(), abroadDeclarationDTO.getGroupUnit(),
//				abroadDeclarationDTO.getTravelTimeStart(),abroadDeclarationDTO.getTravelTimeEnd()));
//
//		List<AbroadDeclarationVO> list2 = new ArrayList<>() ;
//
//		String companyNameSearchId = "";
//		int count = 0;
//		int sum = 0;
// 		if (CollectionUtil.isNotEmpty(list)){
//			//Comparator.comparing(RecruitmentManagementVO::getCompanyCode).reversed() 为降序
//			//按照申报单位编码升序，申报类型编码升序，组团单位编码升序，团长人员编码升序
//			list = list.parallelStream().sorted(Comparator.comparing(AbroadDeclarationVO::getDeclaringUnitCode).thenComparing(AbroadDeclarationVO::getDeclarationsCategoryCode)
//					.thenComparing(AbroadDeclarationVO::getGroupUnitCode).thenComparing(AbroadDeclarationVO::getTravelTime)).collect(Collectors.toList());
//	//		list = list.parallelStream().sorted(Comparator.comparing(AbroadDeclarationVO::getDeclaringUnitCode).thenComparing(AbroadDeclarationVO::getDeclarationsCategoryCode)
//	//				.thenComparing(AbroadDeclarationVO::getGroupUnitCode).thenComparing(AbroadDeclarationVO::getCommanderCode).thenComparing(AbroadDeclarationVO::getTravelTime)).collect(Collectors.toList());
//
//			for(int i =0;i< list.size();i++){
//				if(!companyNameSearchId.equals(list.get(i).getDeclaringUnitId())){
//					if(i>0){
//						AbroadDeclarationVO total = new AbroadDeclarationVO();
//						total.setDeclaringUnitName("小计：" + count);
//						list2.add(total);
//						sum+=count;
//					}
//					companyNameSearchId = list.get(i).getDeclaringUnitId();
//					count = 1;
//				}else{
//					count++;
//				}
//				list2.add(list.get(i));
//			}
//		}
//		sum+=count;
//		AbroadDeclarationVO LastTotal = new AbroadDeclarationVO();
//		LastTotal.setDeclaringUnitName("小计：" + count);
//		list2.add(LastTotal);
//
//		AbroadDeclarationVO SumTotal = new AbroadDeclarationVO();
//		SumTotal.setDeclaringUnitName("总计：" + sum);
//		list2.add(SumTotal);
//
//		reportVO.setData(list2);
//		reportReturnVO.setGrids(reportVO);
//		return reportReturnVO;
//	}
//
//	@Override
//	public List<PageData> findByIds(List<String> formIds) {
//		LambdaQueryWrapper<AbroadDeclaration> queryWrapper = new LambdaQueryWrapper<>();
//		queryWrapper.in(AbroadDeclaration::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
//		List<AbroadDeclaration> abroadDeclarations = list(queryWrapper);
//		List<AbroadDeclarationVO> abroadDeclarationVOS = abroadDeclarationWrapper.entityToVO(abroadDeclarations);
//		List<PageData> pageDataList = new ArrayList<>();
//		try{
//			if (CollectionUtil.isNotEmpty(abroadDeclarationVOS)){
//				for (AbroadDeclarationVO vo : abroadDeclarationVOS){
//					PageData pd = new PageData();
//					pd.put("id", vo.getId());
//					pd.put("UNITNAME", vo.getDeclaringUnitName());
//					pd.put("APPLICANTNAME", vo.getCreateUserName());
//					pd.put("applicantId", vo.getCreateUser());
//					pd.put("applyOrganizationId", vo.getDeclaringUnitId());
//					pd.put("formType", FormTypeConstant.HR_ABROAD_DECLARATION_FORM);
//					pageDataList.add(pd);
//				}
//			}
//
//			return pageDataList;
//		} catch (Exception e) {
//			log.error(ExceptionUtils.getFullStackTrace(e));
//		}
//		return pageDataList;
//	}
//
//	@Override
//	public List<Integer> getFormType() {
//		return Arrays.asList(FormTypeConstant.HR_ABROAD_DECLARATION_FORM);
//	}
//
//	@Override
//	public void goBackToStash(String formId) {
//		handleStatus(Long.valueOf(formId), UNREVIEWED,null);
//	}
//
//	@Override
//	@Transactional(rollbackFor = RuntimeException.class)
//	public String saveAbroadList(String data){
//		YthResult ythResult = new YthResult();
//		//成功的id集合
//		List<String> successIds = new ArrayList<>();
//		//失败的id集合
//		List<String> failIds = new ArrayList<>();
//		//失败的原因
//		List<String> failReasons = new ArrayList<>();
//		//将json字符串转换成list
//		List<AbroadDeclaration> dataList = JSON.parseArray(data, AbroadDeclaration.class);
//		if (CollectionUtil.isNotEmpty(dataList)){
//			Map<String, String> orgSource = orgService.getSourceId();
//			Map<String, String> userSource = userService.getSourceId();
//			//根据datasourceIds 查询出所有的数据
//			List<AbroadDeclaration> list = list(new LambdaQueryWrapper<AbroadDeclaration>().in(AbroadDeclaration::getDataSourceId, dataList.stream().map(AbroadDeclaration::getDataSourceId).toArray()));
//			//如果数据库中有数据，就更新，没有就新增
//			for (AbroadDeclaration entity:dataList){
//				transfer(entity,orgSource,userSource);
//				//id重复略过
//				if (CollectionUtil.isNotEmpty(list)){
//					List<String> olIds = list.stream().map(AbroadDeclaration::getDataSourceId).collect(Collectors.toList());
//					String dataSourceId = entity.getDataSourceId();
//					//判断数据库中是否有数据
//					if (olIds.contains(dataSourceId)){
//						for (AbroadDeclaration oldEntity:list){
//							if (dataSourceId.equals(oldEntity.getDataSourceId())){
//								//判断status是否为0，如果是0，就更新，不是0，就不更新
//								if (CheckStatus.checkCode(oldEntity.getStatus())){
//									successIds.add(dataSourceId);
//									entity.setId(oldEntity.getId());
//									entity.setDataSource(YthConstant.DATA_NINGBO);
//									if (StringUtil.isEmpty(entity.getVersion())) {
//										entity.setVersion("1");
//									} else {
//										entity.setVersion(String.valueOf(Integer.parseInt(oldEntity.getVersion())+1));
//									}
//									entity.setUpdateTime(new Date());
//									saveOrUpdate(entity);
//									list.remove(oldEntity);
//									break;
//								}else {
//									failIds.add(dataSourceId);
//									failReasons.add("dataSourceId:"+dataSourceId+"数据已提交且已经在流程中，无法更新");
//									break;
//								}
//							}
//						}
//					}else {
//						//如果数据库中没有数据，就新增
//						entity.setVersion("1");
//						entity.setCode(formCodeService.getCode(FormTypeConstant.HR_ABROAD_DECLARATION_FORM));
//						entity.setFormType(String.valueOf(FormTypeConstant.HR_ABROAD_DECLARATION_FORM));
//						entity.setDataSource(YthConstant.DATA_NINGBO);
//						saveOrUpdate(entity);
//						successIds.add(entity.getDataSourceId());
//					}
//				}else {
//					//如果数据库中没有数据，就新增
//					entity.setVersion("1");
//					entity.setCode(formCodeService.getCode(FormTypeConstant.HR_ABROAD_DECLARATION_FORM));
//					entity.setFormType(String.valueOf(FormTypeConstant.HR_ABROAD_DECLARATION_FORM));
//					entity.setDataSource(YthConstant.DATA_NINGBO);
//					saveOrUpdate(entity);
//					successIds.add(entity.getDataSourceId());
//				}
//			}
//		} else {
//			failReasons.add("数据为空");
//		}
//		ythResult.setSuccessIds(successIds);
//		ythResult.setFailIds(failIds);
//		ythResult.setFailReason(StringUtils.join(failReasons, ";"));
//		//ythResult转换成json字符串
//		return JSON.toJSONString(ythResult);
//	}
//
//	private void transfer(AbroadDeclaration entity, Map<String, String> orgSourceMap, Map<String, String> userMap){
//		Optional.ofNullable(entity.getDeclaringUnitId()).ifPresent(m ->
//				{
//					String orgId = orgSourceMap.get(m);
//					entity.setDeclaringUnitId(orgId);
//					entity.setCreateCompanyId(orgId);
//				}
//		);
//
//		Optional.ofNullable(entity.getGroupUnit()).ifPresent(m ->
//				{
//					String orgId = orgSourceMap.get(m);
//					Org org = orgService.getById(orgId);
//					entity.setGroupUnit(orgId);
//				}
//		);
//
//		Optional.ofNullable(entity.getCommanderId()).ifPresent(m ->
//				{
//					String userId = userMap.get(m.toString());
//					if (StringUtil.isNotBlank(userId)){
//						entity.setCommanderId(Long.valueOf(userId));
//					}
//				}
//		);
//		Optional.ofNullable(entity.getCompanyId()).ifPresent(m ->
//				{
//					String orgId = orgSourceMap.get(m);
//					entity.setCompanyId(orgId);
//				}
//		);
//	}
//}
